<template>
    <div class="module-page" v-loading="loading">
        <div class="header flex-row flex-item">
            <tz-filter @change="filterChange" :filter-data="filterData" :show-net="false">
                <template v-slot:default="scope">
                    <el-input :maxlength="20" class="table-filter-item" size="small" clearable v-model.trim="scope.data.keyword" placeholder="角色名称"></el-input>
                </template>
            </tz-filter>
            <div class="flex1"></div>
            <div class="right-btn">
                <el-button style="margin-left: 10px"
                           v-if="$auth['setting_role_addRole']"
                           type="primary"
                           @click="addRole"
                           size="small">新增角色</el-button>
            </div>
        </div>
        <tz-table
            ref="tzTable"
            highlight-current-row
            size="mini"
            :data="loadData">
        <el-table-column
                prop="roleName"
                show-overflow-tooltip
                label="角色名称">
            <template slot-scope="scope">
                <high-light :value="scope.row.roleName" :keyword="filterData.keyword"></high-light>
            </template>
        </el-table-column>
        <el-table-column prop="status" label="角色状态" align="center">
            <template slot-scope="scope">
                <el-tag
                        size="mini"
                        :type="scope.row.status ? '' : 'success'"
                >{{scope.row.status ? '启用' : '禁用'}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column
                prop="createTime"
                show-overflow-tooltip
                label="创建时间"
                :formatter="(row) => {
                       return row.createTime ? moment(row.createTime).format('YYYY-MM-DD HH:mm:ss') : '-'
                     }">
        </el-table-column>
        <el-table-column
                prop="tag"
                label="操作">
            <template slot-scope="scope">
                <el-button v-if="$auth['setting_role_update']" @click="editRole(scope.row)" size="small" type="text">编辑</el-button>
                <el-button v-if="$auth['setting_role_delete']" @click="deleteRole(scope.row)" size="small" type="text">删除</el-button>
                <el-button v-if="scope.row.status === 1 && $auth['setting_role_status']" @click="switchStatus(scope.row)" size="small" type="text">停用</el-button>
                <el-button v-else-if="$auth['setting_role_status']" @click="switchStatus(scope.row)" size="small" type="text">启用</el-button>
            </template>
        </el-table-column>
    </tz-table>
        <el-drawer
                :title="drawerTitle"
                :visible.sync="drawer"
                direction="rtl">
            <div class="drawer-content">
                <el-form :model="roleInfo" ref="roleForm" :rules="rules" label-width="80px">
                    <el-form-item label="角色名" prop="roleName">
                        <el-input :maxlength="20" show-word-limit v-model="roleInfo.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色授权" prop="authority">
                        <el-tree
                                :data="treesData"
                                v-if="showTree"
                                ref="menuCodeList"
                                @check-change="checkChange"
                                show-checkbox
                                node-key="code"
                                :check-strictly="true"
                                :default-expanded-keys="[2, 3]"
                                :default-checked-keys="roleInfo.menuCodeList"
                                :props="defaultProps">
                        </el-tree>
                    </el-form-item>
                    <el-form-item>
                        <div class="flex-item flex-row">
                            <div class="flex1"></div>
                            <el-button size="small" @click="drawer = false">取消</el-button>
                            <el-button size="small" type="primary" @click="saveOrUpdateRole">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import tzTable from '@/components/tz-table'
import { mapState, mapActions } from 'vuex'
import moment from 'moment'
export default {
  name: 'roleList',
  components: {
    tzTable
  },
  data() {
    return {
      moment,
      filterData: {
        keyword: '',
      },
      drawer: false,
      showTree: false,
      loading: false,
      drawerTitle: '',
      roleList: [],
      roleInfo: {
        roleId: '',
        roleName: '',
        menuCodeList: []
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ]
      },
      treesData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    drawer: {
      handler(N) {
        if (N) {
          setTimeout(() => {
            this.showTree = true
          }, 100)
        } else {
          this.showTree = false
        }
      },
      immediate: true,
      isEq: 0
    }
  },
  methods: {
    ...mapActions('userInfo', ['updateUserInfo']),
    filterChange(res) {
      this.isEq = res.isEq
      this.refresh()
    },
    addRole() {
      this.editRole({
        roleName: '',
        menuCodeList: []
      })
    },
    switchStatus({ status, roleId }) {
      this.$http.get('/sys/role/updateRoleStatus', {
        params: {
          status: status === 0 ? 1 : 0,
          roleId
        }
      }).then(res => {
        this.$TZmessage.success('操作成功')
      }).catch(err => {
        this.$TZmessage.error(err.msg || '操作失败')
      }).finally(() => {
        this.loading = false
        this.refresh()
      })
    },
    checkChange(node, checked) {
      const checkedKeys = this.$refs.menuCodeList.getCheckedKeys()
      const childrenCodes = []
      const loop = (list) => {
        for (const nodeElement of list) {
          childrenCodes.push(nodeElement.code)
          if (nodeElement.children && nodeElement.children.length) {
            loop(nodeElement.children)
          }
        }
      }
      if (node.children) {
        loop(node.children)
      }
      if (checked) {
        this.roleInfo.menuCodeList = [...checkedKeys, ...childrenCodes]
      } else {
        this.roleInfo.menuCodeList = checkedKeys.filter(code => {
          return !childrenCodes.includes(code)
        })
        this.$refs.menuCodeList.setCheckedKeys(this.roleInfo.menuCodeList)
      }
    },
    getTree() {
      return this.$http.get('/sys/role/getMenuTree', {
        params: {
          userId: this.baseInfo.userId
        }
      }).then(res => {
        this.treesData = res
      })
    },
    refresh() {
      this.$refs.tzTable.refresh(true)
    },
    deleteRole(row) {
      this.$confirm('是否删除角色').then(res => {
        this.loading = true
        this.$http.delete(`/sys/role/delete?roleId=${row.roleId}`).then(res => {
          this.$TZmessage.success('删除成功')
        }).catch(err => {
          this.$TZmessage.error(err.msg || '删除失败')
        }).finally(() => {
          this.loading = false
          this.refresh()
        })
      }).catch(err => {
        console.log('取消执行')
      })

    },
    async editRole(row) {
      this.drawerTitle = row.roleId ? '编辑角色' : '新增角色'
      this.drawer = true
      await this.getTree(row)
      this.$refs.roleForm.resetFields()
      this.roleInfo = { ...row }
    },
    saveOrUpdateRole() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          const { menuCodeList, roleName, roleId, status } = this.roleInfo
          this.loading = true
          const params = {
            createUserId: this.baseInfo.userId,
            menuCodeList,
            roleName,
            status: status || 1
          }
          if (roleId) {
            params.roleId = roleId
          }
          this.$http.post(roleId ? '/sys/role/update' : '/sys/role/save', params).then(res => {
            this.$TZmessage.success(roleId ? '保存成功' : '新增成功')
            this.drawer = false
            this.refresh()
          }).catch(err => {
            this.$TZmessage.error(err.msg || (roleId ? '保存失败' : '新增失败'))
          }).finally(() => {
            this.loading = false
          })
        } else {
          return false;
        }
      });
    },
    loadData(page) {
      this.updateUserInfo()
      const params = { ...page }
      if (this.filterData.keyword) {
        params.roleName = this.filterData.keyword
      }
      params.userId = this.baseInfo.userId
      params.isEq = this.isEq
      return this.$http.get('/sys/role/list', { params }).then(res => {
        return {
          data: res.records || [],
          total: res.total
        }
      }).catch(err => {
        this.$TZmessage.error(err.msg || '获取列表失败')
      })
    },
  },
  computed: {
    ...mapState('userInfo', ['baseInfo']),
  }
}
</script>

<style lang="scss" scoped>
    .module-page {
        padding: 0 27px;
        width: 100%;
        box-sizing: border-box;
        overflow: auto;
        .header {
            height: 69px;
            position: relative;
        }
    }
    .drawer-content {
        padding: 20px;
    }
</style>